package com.toycloud.business.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.toycloud.business.dto.params.*;
import com.toycloud.business.dto.results.CascaderLabelResult;
import com.toycloud.business.dto.results.CascaderLabelTree;
import com.toycloud.business.dto.results.CommonResult;
import com.toycloud.business.service.IFeedbackConfigService;
import com.toycloud.system.domain.dto.FeedBackConfigBrandDTO;
import com.toycloud.system.domain.dto.FeedbackLabelDTO;
import com.toycloud.system.domain.feedback.FeedbackConfig;
import com.toycloud.system.mapper.feedback.FeedbackAnalysisDataMapper;
import com.toycloud.system.mapper.feedback.FeedbackConfigMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author hlchan
 * @version 1.0
 * @date 2024/9/4 17:54
 */
@Service
public class FeedbackConfigServiceImpl implements IFeedbackConfigService {

    @Autowired
    FeedbackConfigMapper feedbackConfigMapper;

    @Override
    public CommonResult<List<FeedbackConfig>> getBaseConfig(FeedbackConfigTypeParams params) {
        // 设置分页参数
        PageHelper.startPage(params.getCurrent(), params.getPageSize());
        if("ascend".equals(params.getCreateTime())){
            params.setCreateTime("asc");
        }else if("descend".equals(params.getCreateTime())){
            params.setCreateTime("desc");
        }
        List<FeedbackConfig> feedbackConfigs = feedbackConfigMapper.selectByType(params);
        Page<FeedbackConfig> feedbackConfigPage = (Page<FeedbackConfig>) feedbackConfigs;

        return CommonResult.Success((int) feedbackConfigPage.getTotal(), feedbackConfigs);
    }

    @Override
    public CommonResult<List<FeedbackConfig>> getUsedConfigList() {
        List<FeedbackConfig> feedbackConfigs = feedbackConfigMapper.selectByFlag(1);
        return CommonResult.Success(feedbackConfigs);
    }

    @Override
    public CommonResult<List<FeedBackConfigBrandDTO>> getBrandConfig(FeedbackConfigPNameParams params) {
//        if (!StringUtils.isEmpty(params.getBrandName())) {
//            FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByTypeAndName(1, params.getBrandName());
//            params.setPid(feedbackConfig.getId().longValue());
//        }
        // 设置分页参数
        PageHelper.startPage(params.getCurrent(), params.getPageSize());
        if("ascend".equals(params.getCreateTime())){
            params.setCreateTime("asc");
        }else if("descend".equals(params.getCreateTime())){
            params.setCreateTime("desc");
        }
        List<FeedbackConfig> feedbackConfigs = new ArrayList<>();
        if(params.getPid()==1){
             feedbackConfigs = feedbackConfigMapper.selectOwnProduct(params);
        }else{
             feedbackConfigs = feedbackConfigMapper.selectByPNameAndName(params);
        }
        Page<FeedbackConfig> feedbackConfigPage = (Page<FeedbackConfig>) feedbackConfigs;

        List<FeedBackConfigBrandDTO> feedBackConfigBrandDTOS = new ArrayList<>();
        feedbackConfigPage.forEach(config -> {
            if (config.getPid() != 0) {
                FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(config.getPid().longValue());
                feedBackConfigBrandDTOS.add(new FeedBackConfigBrandDTO(config, feedbackConfig.getName()));
            } else {
                feedBackConfigBrandDTOS.add(new FeedBackConfigBrandDTO(config, ""));
            }

        });

        return CommonResult.Success((int) feedbackConfigPage.getTotal(), feedBackConfigBrandDTOS);
    }

    @Override
    public CommonResult addBaseConfig(FeedbackConfigParam param) {

        FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByTypeAndName(param.getType(), param.getName(),Integer.valueOf(param.getPid()),param.getWeight(), param.getAlias());
        if (feedbackConfig != null && !feedbackConfig.getFlag().toString().equals("0")) {
            return CommonResult.Fail("该名称已存在！");
        }
        if (feedbackConfig == null) feedbackConfig = new FeedbackConfig();
        feedbackConfig.setPid(param.getPid());
        feedbackConfig.setName(param.getName());
        feedbackConfig.setFlag('1');
        feedbackConfig.setType(param.getType());
        feedbackConfig.setCreateTime(new Date());
        feedbackConfig.setUpdateTime(new Date());
        feedbackConfig.setAlias(param.getAlias());
        feedbackConfig.setWeight(param.getWeight());
        //todo list 添加用户信息
//       feedbackConfig.setLastOperator();

        if (feedbackConfig.getId() != null && feedbackConfig.getId() > 0) {
            return feedbackConfigMapper.updateByPrimaryKey(feedbackConfig) > 0 ? CommonResult.Success() : CommonResult.Fail();
        }
        return feedbackConfigMapper.insertSelective(feedbackConfig) > 0 ? CommonResult.Success() : CommonResult.Fail();
    }

    @Override
    @Transactional
    public CommonResult removeBaseConfig(FeedbackConfigIdParam param) {
        FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(param.getId());

        if (feedbackConfig == null) return CommonResult.Fail("未找到数据！");

        List<FeedbackConfig> feedbackConfigList = feedbackConfigMapper.selectByPid(feedbackConfig.getId());
        CommonResult commonResult = null;
        if (!CollectionUtils.isEmpty(feedbackConfigList)) {
            for (int i = 0; i < feedbackConfigList.size(); i++) {
                FeedbackConfig f = feedbackConfigList.get(i);
                commonResult = removeBaseConfig(new FeedbackConfigIdParam(f.getId()));
                //删除统计数据
                removeAnalysisData(f);
                if (commonResult.getCode() != 0) {
                    return commonResult;
                }
            }
        }

        //删除统计数据
        removeAnalysisData(feedbackConfig);
        return feedbackConfigMapper.deleteByPrimaryKey(feedbackConfig.getId().longValue()) > 0 ? CommonResult.Success() : CommonResult.Fail();
    }

    public void removeAnalysisData(FeedbackConfig f) {
        if ("1".equals(f.getType())) {
            feedbackAnalysisDataMapper.deleteByBrand(f.getId());
        }
        if ("2".equals(f.getType())) {
            feedbackAnalysisDataMapper.deleteByProduct(f.getId());
        }
        if ("3".equals(f.getType())) {
            feedbackAnalysisDataMapper.deleteByStep(f.getId());
        }
        if ("4".equals(f.getType())) {
            feedbackAnalysisDataMapper.deleteBySource(f.getId());
        }
    }

    @Override
    public CommonResult updateBaseConfig(FeedbackConfigUpadateParam param) {
        FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(param.getId());
        if (feedbackConfig == null) return CommonResult.Fail("未找到数据！");

        feedbackConfig.setName(param.getName());
        feedbackConfig.setType(param.getType());
        feedbackConfig.setAlias(param.getAlias());
        feedbackConfig.setWeight(param.getWeight());
        if (param.getPid() > 0) feedbackConfig.setPid(param.getPid());
        //todo list 添加用户信息
//        feedbackConfig.setLastOperator()

        return feedbackConfigMapper.updateByPrimaryKey(feedbackConfig) > 0 ? CommonResult.Success() : CommonResult.Fail();
    }


    @Override
    public CommonResult<List<FeedbackLabelDTO>> getFeedbackLabelList(FeedbackLabelParams params) {
        String[] typeArr = {"5", "6", "7"};
        List<FeedbackConfig> configList = feedbackConfigMapper.selectByTypes(typeArr);
        // 设置分页参数
        PageHelper.startPage(params.getCurrent(), params.getPageSize());
        List<FeedbackConfig> feedbackLabelConfigList = new ArrayList<>();
        List<FeedbackLabelDTO> feedbackLabelDTOList = new ArrayList<>();
        //优先三级标签
        if (StringUtils.isNotEmpty(params.getThreeLevelLabel())) {
            feedbackLabelConfigList = feedbackConfigMapper.selectByTypeAndLikeName(7, params.getThreeLevelLabel());
            feedbackLabelDTOList = convertLevelLabel(configList, feedbackLabelConfigList, feedbackLabelDTOList);
        } else if (StringUtils.isNotEmpty(params.getSecondLevelLabel())) {
            //二级标签
            feedbackLabelConfigList = feedbackConfigMapper.selectByTypeAndLikeSecondLevelLabel(6, params.getSecondLevelLabel());
            feedbackLabelDTOList = convertLevelLabel(configList, feedbackLabelConfigList, feedbackLabelDTOList);
        } else if (StringUtils.isNotEmpty(params.getFirstLevelLabel())) {
            //一级标签
            feedbackLabelConfigList = feedbackConfigMapper.selectByTypeAndLikeFirstLevelLabel(5, params.getFirstLevelLabel());
            feedbackLabelDTOList = convertLevelLabel(configList, feedbackLabelConfigList, feedbackLabelDTOList);
        } else if (params.getPid() == 0) {
            //查找全部
            feedbackLabelConfigList = feedbackConfigMapper.selectByTypeValue(7);
            feedbackLabelDTOList = convertLevelLabel(configList, feedbackLabelConfigList, feedbackLabelDTOList);
        } else {
            //选中节点
            feedbackLabelConfigList = feedbackConfigMapper.selectByTypeValueAndPid(7, params.getPid());
            feedbackLabelDTOList = convertLevelLabel(configList, feedbackLabelConfigList, feedbackLabelDTOList);
        }
        Page<FeedbackConfig> feedbackLabelPage = (Page<FeedbackConfig>) feedbackLabelConfigList;
        return CommonResult.Success((int) feedbackLabelPage.getTotal(), feedbackLabelDTOList);
    }

    public List<FeedbackLabelDTO> convertLevelLabel(List<FeedbackConfig> configList, List<FeedbackConfig> feedbackLabelConfigList, List<FeedbackLabelDTO> feedbackLabelDTOList) {

        feedbackLabelConfigList.forEach(x -> {
            FeedbackLabelDTO dto = new FeedbackLabelDTO();
            dto.setId(x.getId());
            dto.setThreeLevelLabel(x.getName());
            dto.setAlias(x.getAlias());
            dto.setWeight(x.getWeight());
            //查找一二级节点
            FeedbackConfig secondLevelLabelConfig = configList.stream()
                    .filter(y -> ("6".equals(y.getType())))
                    .filter(y -> y.getId().equals(x.getPid()))
                    .findFirst()
                    .orElse(null);
            if (secondLevelLabelConfig != null) {
                dto.setSecondLevelLabel(secondLevelLabelConfig.getName());
                dto.setPid(secondLevelLabelConfig.getId());
                FeedbackConfig firstLevelLabelConfig = configList.stream()
                        .filter(y -> ("5".equals(y.getType())))
                        .filter(y -> y.getId().equals(secondLevelLabelConfig.getPid()))
                        .findFirst()
                        .orElse(null);
                if (firstLevelLabelConfig != null) {
                    dto.setFirstLevelLabelId(firstLevelLabelConfig.getId());
                    dto.setFirstLevelLabel(firstLevelLabelConfig.getName());
                }
            }
            feedbackLabelDTOList.add(dto);
        });
        return feedbackLabelDTOList;

    }


    @Override
    public CommonResult<Boolean> SaveFeedbackLabelParam(SaveFeedbackLabelParams param) {
        boolean result = false;
        FeedbackConfig existConfig = feedbackConfigMapper.selectByTypeAndName(Integer.valueOf(param.getType()), param.getLabel(),Integer.valueOf(param.getPid()),param.getWeight(),param.getAlias());
        if (existConfig != null) {
            return CommonResult.Fail("标签重复！");
        }
        if (param.getId() == 0L) {
            FeedbackConfig feedbackConfig = new FeedbackConfig();
            feedbackConfig.setPid(Integer.valueOf(param.getPid()));
            feedbackConfig.setName(param.getLabel());
            feedbackConfig.setFlag("1");
            feedbackConfig.setType(param.getType());
            feedbackConfig.setCreateTime(new Date());
            feedbackConfig.setUpdateTime(new Date());
            feedbackConfig.setAlias(param.getAlias());
            feedbackConfig.setWeight(param.getWeight());
            result = feedbackConfigMapper.insertSelective(feedbackConfig) > 0;
        } else {
            FeedbackConfig existFeedbackConfig = feedbackConfigMapper.selectByPrimaryKey(param.getId());
            if (StringUtils.isNotEmpty(param.getPid())) {
                existFeedbackConfig.setPid(Integer.valueOf(param.getPid()));
            }
            existFeedbackConfig.setAlias(param.getAlias());
            existFeedbackConfig.setWeight(param.getWeight());
            existFeedbackConfig.setName(param.getLabel());
            result = feedbackConfigMapper.updateByPrimaryKeySelective(existFeedbackConfig) > 0;
            existFeedbackConfig.setUpdateTime(new Date());
        }
        return CommonResult.Success(result);
    }

    @Override
    public CommonResult<CascaderLabelResult> getCascaderLabel() {
        String[] typeArr = {"5", "6", "7"};
        CascaderLabelResult result = new CascaderLabelResult();
        List<FeedbackConfig> labelList = feedbackConfigMapper.selectByTypes(typeArr);
        List<CascaderLabelTree> tree = GetLabelChildTree(labelList, 0);
        result.setLabelList(tree);
        return CommonResult.Success(result);
    }

    @Override
    public CommonResult<CascaderLabelResult> getCascaderTypeLabel() {
        String[] typeArr = {"1", "10", "2"};
        CascaderLabelResult result = new CascaderLabelResult();
        List<FeedbackConfig> labelList = feedbackConfigMapper.selectByTypes(typeArr);
        List<CascaderLabelTree> tree = GetLabelChildTree(labelList, 0);
        result.setLabelList(tree);
        return CommonResult.Success(result);
    }

    @Override
    public CommonResult<CascaderLabelResult> getCascader(String[] types) {
        CascaderLabelResult result = new CascaderLabelResult();
        List<FeedbackConfig> labelList = feedbackConfigMapper.selectByTypes(types);
        List<CascaderLabelTree> tree = GetLabelChildTree2(labelList, 0);
        result.setLabelList(tree);
        return CommonResult.Success(result);
    }

    @Autowired
    private FeedbackAnalysisDataMapper feedbackAnalysisDataMapper;

    @Override
    public CommonResult<Boolean> deleteLabel(long id, int pid) {
        feedbackConfigMapper.deleteByPrimaryKey(id);
        //todo:待优化
        feedbackAnalysisDataMapper.deleteByThreeLevelLabel(id);
        if (pid != 0) {
            feedbackConfigMapper.deleteByPid(pid);
            //todo:待优化
            feedbackAnalysisDataMapper.deleteByFirstLevelLabel(pid);
            feedbackAnalysisDataMapper.deleteBySecondLevelLabel(pid);
        }
        return CommonResult.Success(true);
    }

    //    public static List<CascaderLabelTree> GetLabelChildTree(List<FeedbackConfig> list, long Id) {
//        List<CascaderLabelTree> tree = new ArrayList<>();
////        List<long> packageIds = new List<long>();
//        List<FeedbackConfig> ChildList = GetChildList(list, Id);
//            for (FeedbackConfig item : ChildList) {
//                CascaderLabelTree treeB = new CascaderLabelTree();
//                treeB.setLabel(item.getName());
//                treeB.setValue(item.getId().toString());
//                treeB.children = GetLabelChildTree(list, item.getId());
//                tree.add(treeB);
//            }
//
//        return tree;
//    }
    public static List<CascaderLabelTree> GetLabelChildTree(List<FeedbackConfig> list, long Id) {
        List<CascaderLabelTree> tree = new ArrayList<>();
        List<FeedbackConfig> ChildList = GetChildList(list, Id);

        for (FeedbackConfig item : ChildList) {
            CascaderLabelTree treeB = new CascaderLabelTree();
            treeB.setLabel(item.getName());

            //标签管理目录树
            treeB.setKey(item.getId().toString());
            treeB.setPid(item.getPid());
            treeB.setType((String) item.getType());
            //级联
            // 判断是否有子项，如果有则将 value 设置为 label
            if (GetChildList(list, item.getId()).isEmpty()) {
                // 如果没有子项，使用数字 value
                treeB.setValue(item.getId().toString());
            } else {
                // 如果有子项，使用 label 作为 value
                treeB.setValue(item.getName());
            }

            treeB.children = GetLabelChildTree(list, item.getId());
            tree.add(treeB);
        }

        return tree;
    }

    public static List<CascaderLabelTree> GetLabelChildTree2(List<FeedbackConfig> list, long Id) {
        List<CascaderLabelTree> tree = new ArrayList<>();
        List<FeedbackConfig> ChildList = GetChildList(list, Id);

        for (FeedbackConfig item : ChildList) {
            CascaderLabelTree treeB = new CascaderLabelTree();
            treeB.setLabel(item.getName());

            //标签管理目录树
            treeB.setKey(item.getId().toString());
            treeB.setPid(item.getPid());
            treeB.setType((String) item.getType());
            treeB.setValue(item.getId().toString());

            treeB.children = GetLabelChildTree2(list, item.getId());
            tree.add(treeB);
        }

        return tree;
    }

    public static List<FeedbackConfig> GetChildList(List<FeedbackConfig> list, long id) {
        List<FeedbackConfig> childList = new ArrayList<>();
        if (list != null) {
            childList = list.stream().filter(x -> x.getPid() == id).collect(Collectors.toList());
        }

        return childList;
    }

//    public CascaderLabelResult generateCascaderLabel(List<FeedbackLabel> labelList) {
//        CascaderLabelResult result = new CascaderLabelResult();
//        Map<String, List<FeedbackLabel>> map1 = labelList.stream().collect(Collectors.groupingBy(FeedbackLabel::getFirstLevelLabel));
//        for (Map.Entry<String, List<FeedbackLabel>> entry1 : map1.entrySet()) {
//            CascaderLabelResult.Label1 label1 = new CascaderLabelResult.Label1()
//                    .setLabel(entry1.getKey())
//                    .setValue(entry1.getKey());
//            Map<String, List<FeedbackLabel>> map2 = entry1.getValue().stream().collect(Collectors.groupingBy(FeedbackLabel::getSecondLevelLabel));
//            for (Map.Entry<String, List<FeedbackLabel>> entry2 : map2.entrySet()) {
//                CascaderLabelResult.Label2 label2 = new CascaderLabelResult.Label2()
//                        .setLabel(entry2.getKey())
//                        .setValue(entry2.getKey());
//                label1.getChildren().add(label2);
//                Map<String, List<FeedbackLabel>> map3 = entry1.getValue().stream().collect(Collectors.groupingBy(FeedbackLabel::getThreeLevelLabel));
//                for (Map.Entry<String, List<FeedbackLabel>> entry3 : map3.entrySet()) {
//                    entry3.getValue().forEach(x -> {
//                        CascaderLabelResult.ThreeLabel label3 = new CascaderLabelResult.ThreeLabel()
//                                .setLabel(x.getThreeLevelLabel())
//                                .setValue(x.getId());
//                        label2.getChildren().add(label3);
//                    });
//
//                }
//            }
//            result.getLabelList().add(label1);
//        }
//        return result;
//    }
}
